<template>
  <el-container>
    <el-header class="header">
      <div class="left">
        <el-icon @click="$router.go(-1)"><ArrowLeftBold /></el-icon>
        <div class="nameInfo">
          <div class="title">{{ tableName }}</div>
          <!-- <div class="recent">最近保存:1分钟前</div> -->
        </div>
      </div>
      <div class="middle">
        <el-steps :active="curStep" finish-status="success" align-center>
          <el-step v-for="(step, index) in showSteps" :key="index" :title="step" />
        </el-steps>
      </div>
      <div class="right">
        <el-button
          @click="goBack"
          style="background-color: #24ada2; color: #fff"
          v-if="curStep != 0"
        >上一步</el-button
        >
        <el-button
          v-if="curStep == showSteps.length - 1"
          @click="publish"
          style="background-color: #24ada2; color: #fff"
        >发布</el-button
        >
        <el-button @click="save" type="warning">暂存</el-button>
        <el-button @click="toNextStep" style="background-color: #24ada2; color: #fff"
        >保存并下一步</el-button
        >
      </div>
    </el-header>
    <el-main class="main">
      <div class="content">
        <base-form-design
          ref="formDataList"
          v-model:data="formModelData"
          v-if="curStep == 0"
          @is-showmodel-design="isShowmodelDesign"
          @is-show-flow-design="isShowFlowDesign"
          @go-next-step="goNextStep"
          @getcurrent-name="getcurrentName"
          :curStep="curStep"
          @ent-blur="entBlur"
          @page-type-change="handlePageTypeChange"
          :dataSourceInfo="dataSource"
        />
        <avue-form-design
          v-if="showSteps[curStep] == '表单设计'"
          ref="formDesignRef"
          :seeData="seeData"
          :pageVersionId="pageVersionId"
          :formModelEntities="formModelEntities"
          :formModelDataFromDesign="formModelData"
          :options="formDesignOptions"
          :default-values="formDesignDefaultValues"
          :forApp="formModelData.isAppletShow == 'Y'"
          @submit="handleFormDesignSubmit"
          @form-id="formIdFn"
          @change-options="handleOptionsChange"
        />
        <!-- 列表设计 -->
        <!-- <div v-if="showSteps[curStep] == '列表设计'">
          <form-page
            :pageVersionId="pageVersionId"
            :formPageData="formPageData"
            :options="formDesignOptions"
          />
        </div> -->
      </div>
    </el-main>
  </el-container>
</template>
<script>
import baseFormDesign from '@code/views/code/components/base-form-desgin/index.vue'
// import FormPage from '@code/views/code/components/form-page-desgin/index.vue'
// import { AvueFormDesign } from '@code/components/anvil-code-low-design'
import {
  savePageBasicInfo,
  copyPageBasicInfo,
  selectByPageVersionId,
  saveForm,
  publishPage,
  saveList
} from '@code/api/code/page'
import { validatenull } from '@/utils/validate'
import { getPinyin } from '@/api/common'
// import { randomString } from "@/utils/zmids";
import * as anvil from '@/utils/anvil'
// import { useProcessStore } from '@code/store'
import { ElMessage } from 'element-plus'
// import { useTagsView } from '@/hooks/web/useTagsView'
import { useRouter } from 'vue-router'
import { useTagsViewStore } from '@/store/modules/tagsView'
import { useCodeStore } from '@code/store'
import { Base64 } from 'js-base64'

export default {
  name: 'PageEdit',
  components: {
    baseFormDesign,
    // AvueFormDesign
  },
  data() {
    return {
      isValid: true,
      tableName: '未命名表单',
      steps: ['基础信息', '表单设计', '列表设计'],
      curStep: 0,
      tabsType: '', // 控制模型设计显示
      flowType: '', // 控制流程设定显示
      showFlowDesign: true,
      formModelVersionId: '',
      formModelVersioneditId: '',
      formModelData: {},
      seeData: '0',
      formModelEntities: {},
      formPageData: {},
      entIndex: 0,
      totalEntIndex: 0,
      formDesignOptions: {},
      formDesignDefaultValues: {
        select: [
          {
            label: '默认值',
            value: '默认值',
            hide: true
          }
        ]
      },
      formId: '',
      dataTypeMap: [],
      paramsFormData: {},
      dictDataList: [],
      dataSource: {},
      jsonData: null,
      authJson: [],
      permissionJson: [],
      additionDesignData: {
        submitWarnSetting: {}
      },
      pageVersionId: '', // 页面版本id
      pageType: '', // 页面类型
      loaded: false, // 记录页面是否加载完成
    }
  },
  computed: {
    // 用于筛选场景功能页面
    showSteps() {
      return this.steps.filter((step) => {
        if (step == '表单设计') {
          return this.pageType !== 'Q'
        } else if (step == '列表设计') {
          return this.pageType !== 'F'
        }
        return true
      })
    }
  },
  activated(){
    if(this.loaded){
      console.log('activated')
      this.getDictsData()
      this.initData()
      this.getSenceDetailsInfo()
    }
  },
  async mounted() {
    this.getDictsData()
    this.initData()
    await this.getSenceDetailsInfo()
    this.loaded = true
  },
  methods: {
    async publish() {
      if (this.showSteps[this.curStep] == '表单设计') {
        this.saveFormDataInfo(this.handlePublishSaveSuccess)
      } else if (this.showSteps[this.curStep] == '列表设计') {
        this.savePageInfo(this.handlePublishSaveSuccess)
      }
    },
    getcurrentName(e) {
      this.tableName = e
    },
    initData() {
      this.curStep = 0
      this.formModelData = {
        pageName: '',
        pageCode: '',
        pageDesc: '',
        groupId: this.$route.query.groupId,
        pageIcon: '',
        withMenu: 'N',
        appId: this.$route.query.appId,
        pageType: 'F',
        pageModelId: []
      }
      this.pageType = this.formModelData.pageType
      this.formModelEntities = {
        isDeploy: 'N',
        entities: []
      }
      this.formPageData = {
        searchColumnsData: [],
        operateButtonsData: [],
        tableColumnsData: [],
        // 表格行设置
        tableRow: {
          align: 'center',
          selectionPrompt: 'Y',
          flipPageSelection: 'N'
        }
      }
    },
    initShow(versionInfo, entitiesList) {
      this.initData()
      if (versionInfo) {
        // this.seeData = versionInfo.model.seeData
        this.formModelData = versionInfo.codePageInfoDomain
        this.formModelData.pageModelId = versionInfo.codePageInfoDomain.pageModelId.split(',')
        this.pageVersionId = versionInfo.pageVersionId
        this.tableName = this.formModelData.pageName
        this.curStep += parseInt(this.$route.query.step || 0)
        // this.formModelData.background = versionInfo.model.iconPath.split(';')[1]
        // this.formModelData.isDeploy = versionInfo.isDeploy
        // if (versionInfo.withFlow === 'Y') {
        //   this.formModelData.sceneType = 'flowForm'
        // } else {
        //   this.formModelData.sceneType = 'onlyForm'
        // }
        // this.formModelVersionId = versionInfo.formModelVersionId
        //返回 entitiesList
        // if (entitiesList.datasourceId) {
        //   this.dataSource = entitiesList.datasourceInfoDomain
        //   this.dataSource.datasourceId = entitiesList.datasourceId
        // }
        // entitiesList.entities.forEach((item) => {
        //   item.formEntityDescId = item.formEntityName
        // })
        // this.formModelEntities = {
        //   entities: entitiesList.entities,
        //   isDeploy: versionInfo.isDeploy
        // }
        // // 获取当前最大表排序号并记录
        // if (entitiesList.entities.length) {
        //   this.totalEntIndex = Number(entitiesList.entities[entitiesList.entities.length - 1].sort)
        // }
      }
      // this.activeStep = 1;
      // this.changeStep();
      // this.designForm.visible = true;
    },
    async getSenceDetailsInfo() {
      if (this.$route.query.type == 'edit') {
        let model = await selectByPageVersionId(this.$route.query.id)
        // let entities = await selectByFormEntitiesVersionId(this.$route.query.id)
        // this.formModelData.version = model.data.version
        // this.formModelData.formModelId = model.data.formModelId
        // this.formModelVersioneditId = model.data.formModelVersionId
        model.data.codePageInfoDomain.seeData = '1'
        this.initShow(model.data)
        // selectByFormModelVersionId(this.$route.query.id).then(res => {
        //   this.formModelData.version = res.data.version
        //   this.formModelData.formModelId = res.data.formModelId
        //   this.formModelVersioneditId = res.data.formModelVersionId
        //   res.data.model.seeData = '1'
        //   this.initShow(res.data)
        // })
      }
      if (this.$route.query.type == 'copy'){
        let model = await selectByPageVersionId(this.$route.query.id);
        model.data.codePageInfoDomain.seeData = '0';
        model.data.codePageInfoDomain.pageName = model.data.codePageInfoDomain.pageName + '副本';
        model.data.codePageInfoDomain.pageCode = model.data.codePageInfoDomain.pageCode + 'copy';
        this.initShow(model.data);
      }
    },
    getDictsData() {
      // 获取字典类型数据
      this.getDicts('MOD_REFLECTION_DATA_LENGTH').then((response) => {
        this.dictDataList = response.data
      })
    },
    // 是否显示模型设计tab
    isShowmodelDesign(n) {
      this.tabsType = n
      // if(n == 'modeling') {
      //   this.steps = ["基础信息", "模型设计", "表单设计", "列表设计", "流程设定", "表单发布", "数据管理"]
      // } else {
      //   this.steps = ["基础信息", "表单设计", "列表设计", "流程设定", "表单发布", "数据管理"]
      // }
    },
    isShowFlowDesign(n) {
      this.flowType = n
    },
    handleFormDesignSubmit(json) {
      let params = this.$route.query
      if (validatenull(params)) {
        return false
      }
      let result = JSON.stringify(json)
    },
    validatorForm: function (e) {
      if (anvil.checkInSpecialCharacters(this.formModelData.formModelName)) {
        this.msgError('业务对象名称不可以包含特殊字符')
        return false
      }
      if (anvil.checkIsChinese(this.formModelData.formModelCode)) {
        this.msgError('业务对象编码不可以包含中文或特殊字符')
        return false
      }

      return this.checkEntityFunc(this.formModelEntities.entities)
    },
    checkEntityFunc: function (e) {
      if (e.length < 1) {
        this.$message.error('请添加实体对象！')
        return false
      }
      for (let index = 0; index < e.length; index++) {
        const entity = e[index]
        if (!entity.formEntityDesc) {
          this.msgError(`第${index + 1}个实体描述不可以为空`)
          return false
        } else if (!entity.formEntityName) {
          this.msgError(`第${index + 1}个实体名称不可以为空`)
          return false
        } else {
          if (false == this.checkEntityColumnFunc(entity)) {
            return false
          }
        }
      }
      return true
    },
    checkEntityColumnFunc: function (entity) {
      if (entity.columns.length <= 0) {
        this.msgError(`实体${entity.formEntityDesc}的字段不可以为空`)
        return false
      }
      var n = new RegExp('^\\d*(?:\\.\\d{1,2})?$')
      var i = {}
      for (let index = 0; index < entity.columns.length; index++) {
        const column = entity.columns[index]
        if (!column.formEntityColumnDesc) {
          this.msgError(`实体${entity.formEntityDesc}的第${index + 1}个字段名不可以为空`)
          return false
        }
        if (column.formEntityColumnDesc && column.formEntityColumnDesc.length > 20) {
          column.formEntityColumnDesc = column.formEntityColumnDesc.substring(0, 20)
          column.formEntityColumnName = column.formEntityColumnName.substring(0, 20)
          this.msgError(`实体${entity.formEntityDesc}的第${index + 1}个字段名长度不可以超过20`)
          return false
        }
        if (!column.formEntityColumnName) {
          this.msgError(`实体${entity.formEntityDesc}的第${index + 1}个名称不可以为空`)
          return false
        }
      }
    },
    // 新增实体
    addEntityRows: function () {
      if (this.formModelEntities.entities.length > 0 && false === this.validatorForm()) {
        return
      }
      this.entIndex = this.formModelEntities.entities.length
      this.totalEntIndex++
      var t = {
        index: this.entIndex,
        sort: this.totalEntIndex,
        formEntityDesc: '',
        formEntityName: '',
        isMain: 'N',
        isExternal: 'N',
        relationType: '11',
        columns: []
      }
      if (this.formModelEntities.entities.length <= 0) {
        this.entIndex = 0
        t.index = 0
        t.sort = 1
        t.isMain = 'Y'
        t.relationType = ''
      }
      this.formModelEntities.entities.push(t)
    },
    deleteEntityRows: function (index) {
      // 只有当目前不存在子表的时候才能删除主表
      if (
        this.formModelEntities.entities[index].isMain === 'Y' &&
        this.formModelEntities.entities.length !== 1
      ) {
        this.$message.error('当前还存在子实体！')
        return
      }
      this.formModelEntities.entities.splice(index, 1)
      if (this.entIndex > 0 && this.entIndex >= this.formModelEntities.entities.length) {
        this.entIndex--
      }
    },
    chineseFormat: function (e, t, n, i, o) {
      if (Array.isArray(t) && t[i]['tableName']) {
        return false
      }
      // eslint-disable-next-line @typescript-eslint/no-this-alias
      var a = this,
        s = document.getElementById(e),
        l = null
      null === s ||
        !o ||
        (l && clearTimeout(l),
        (l = setTimeout(function () {
          getPinyin(o).then(function (res) {
            if (a.stepType === 'model') {
              a.formModelData.formModelCode = res.data
            } else {
              t[i][n] = res.data
            }
            anvil.checkIsChinese(res.data)
          })
        }, 500)))
    },
    entBlur: function (e) {
      if (
        this.formModelEntities.entities[this.entIndex] &&
        this.formModelEntities.entities[this.entIndex].columns.length > 0 &&
        !this.validatorForm()
      ) {
        return !1
      }
    },
    checkEntityLength(item) {
      const { formEntityDesc, formEntityName } = item
      if (formEntityDesc.length > 20) {
        this.$message.error('实体描述长度不能超过20！')
        item.formEntityDesc = formEntityDesc.substring(0, 20)
        item.formEntityName = formEntityName.substring(0, 20)
      }
    },
    getFormModelEntities(data) {
      this.formModelEntities = {
        entities: data
      }
    },
    formIdFn(val) {
      this.formId = val
    },
    // 接收基础信息上传excel传来的数据信息
    getModelEntities(data) {
      this.formModelEntities = {
        entities: data
      }
    },
    getDataSourceInfo(data) {
      if (data != undefined) {
        this.dataSource = data
      }
    },
    goNextStep() {
      this.handleSubmit(true)
    },
    save() {
      this.handleSubmit(false)
    },
    toNextStep() {
      this.handleSubmit(true)
    },
    goBack() {
      this.formModelData.version = this.formModelData.version
      if (this.curStep >= 1) {
        this.curStep -= 1
      }
    },
    async handleSubmit(isNext) {
      if (this.showSteps[this.curStep] == '基础信息') {
        // 基础信息
        this.saveBaseInfo(() => this.handleSaveSuccess(isNext))
      } else if (this.showSteps[this.curStep] == '表单设计') {
        // 表单设计
        this.saveFormDataInfo(() => this.handleSaveSuccess(isNext))
      }
      // else if (this.showSteps[this.curStep] == '模型设计') {
      //   // 模型设计
      //   this.saveModelEntity()
      // }
      else if (this.showSteps[this.curStep] == '列表设计') {
        // 列表设计
        this.savePageInfo(() => this.handleSaveSuccess(isNext))
        // this.publishFormInfo()
      }
      // else if (this.showSteps[this.curStep] == '流程设定') {
      //   // 流程设定
      //   this.saveFlowInfo()
      // } else if (this.showSteps[this.curStep] == '附加功能') {
      //   this.saveAdditionInfo()
      // } else if (this.showSteps[this.curStep] == '表单发布') {
      //   // 表单发布
      //   await this.publishDataAuth()

      // }
    },
    // 保存基础信息
    saveBaseInfo(callback) {
      this.$refs['formDataList'].validate((valid) => {
        const params = {
          ...this.formModelData,
          pageModelId: this.formModelData.pageModelId.join(',')
        }
        if (this.$route.query.type == 'edit') {
          savePageBasicInfo(params).then((res) => {
            if (res.msg == '成功') {
              // this.paramsFormData = res.data
              // this.formModelVersionId = res.data.formModelVersionId
              // this.formModelData.version = res.data.version
              this.pageVersionId = res.data
              this.$message.success('基础信息保存成功！')
              if (typeof callback == 'function') {
                callback()
              }
            } else {
              this.$message.success('基础信息保存失败！')
            }
          })
        } else if (this.$route.query.type == 'add') {
          savePageBasicInfo(params).then((res) => {
            if (res.msg == '成功') {
              this.pageVersionId = res.data
              this.$message.success('基础信息保存成功！')
              if (typeof callback == 'function') {
                callback()
              }
            } else {
              this.$message.success('基础信息保存失败！')
            }
          })
        }else if (this.$route.query.type == 'copy') {
          copyPageBasicInfo(params).then((res) => {
            if (res.msg == '成功') {
              this.pageVersionId = res.data
              this.$message.success('基础信息保存成功！')
              if (typeof callback == 'function') {
                callback()
              }
            } else {
              this.$message.success('基础信息保存失败！')
            }
          })
        }
      })
    },
    async saveFormDataInfo(callback) {
      // const processStore = useProcessStore()
      // 保存表单设计数据
      this.$refs.formDesignRef.getData().then((jsonData) => {
        jsonData.column.forEach((item) => {
          this.dictDataList.forEach((n) => {
            if (item.type == n.dictLabel) {
              item.columnLength = n.columnLength
              item.decimalLength = n.decimalLength
            }
          })
          if (item.isRequired == undefined) {
            item.isRequired = 'Y'
          }
          if (item.isPrimaryKey == undefined) {
            item.isPrimaryKey = 'N'
          }
          if (item.isPkAuto == undefined) {
            item.isPkAuto = 'N'
          }
          if (item.isHidden == undefined) {
            item.isHidden = 'N'
          }
          if (item.children == undefined) {
            // 如果是模型设计，formkey由entity决定，如果是表单模式，formkey由模型名和子表单名决定
            if (item.formEntityName && item.formEntityDesc) {
              item.formKey = item.formEntityName
              item.formName = item.formEntityDesc
            } else {
              item.formKey = this.formModelData.pageCode
              item.formName = this.formModelData.pageName
            }
            item.isMain = 'Y'
          } else {
            // item.formKey = item.prop
            // item.formName = item.label;
            item.children.column.forEach((t) => {
              this.dictDataList.forEach((n) => {
                if (t.type == n.dictLabel) {
                  t.columnLength = n.columnLength
                  t.decimalLength = n.decimalLength
                }
              })
              if (t.formEntityName && t.formEntityDesc) {
                t.formKey = t.formEntityName
                t.formName = t.formEntityDesc
              } else {
                t.formKey = item.formKey
                t.formName = item.label
              }

              item.isMain = 'N'
              if (t.isRequired == undefined) {
                t.isRequired = 'Y'
              }
              if (t.isPrimaryKey == undefined) {
                t.isPrimaryKey = 'N'
              }
              if (t.isPkAuto == undefined) {
                t.isPkAuto = 'N'
              }
              if (t.isHidden == undefined) {
                t.isHidden = 'N'
              }
            })
          }
        })
        if (this.formId) {
          this.formModelData.formId = this.formId
          this.formModelData.pageVersionId = this.pageVersionId
        }
        this.jsonData = jsonData
        // this.handleJsonDataTrans(jsonData);
        return saveForm({
          pageFormKey: this.formModelData.pageCode,
          pageFormName: this.formModelData.pageName,
          pageVersionId: this.pageVersionId,
          pageFormJson: Base64.encode(JSON.stringify(jsonData))
        }).then((res) => {
          if (res.code == '200') {
            this.msgSuccess('表单信息保存成功')
            // processStore.processformColumn(jsonData.column)
            if (typeof callback == 'function') {
              callback()
            }
          } else {
            this.msgError('表单信息保存失败')
          }
        })
      })
    },
    // 保存列表设计
    async savePageInfo(callback) {
      return saveList({
        pageVersionId: this.pageVersionId,
        searchJson: JSON.stringify(this.formPageData.searchColumnsData),
        showJson: JSON.stringify(this.formPageData.tableColumnsData),
        buttonJson: JSON.stringify(this.formPageData.operateButtonsData)
      }).then((res) => {
        if (res.msg == '成功') {
          this.$message.success('列表设计保存成功！')
          if (typeof callback == 'function') {
            callback()
          }
          // ++this.curStep
        } else {
          this.$message.error('列表设计保存失败！')
        }
      })
    },
    // 表单发布
    publishFormInfo(callback) {
      publishPage(this.pageVersionId).then((res) => {
        if (res.code == '200') {
          ElMessage.success('发布成功')
          if (typeof callback == 'function') {
            callback()
          }
        } else {
          ElMessage.error('发布失败')
        }
      })
    },
    handleOptionsChange(options) {
      this.formDesignOptions = options
    },
    handlePageTypeChange(value) {
      this.pageType = value
    },
    handleSaveSuccess(isNext) {
      const tagsViewStore = useTagsViewStore()
      if (isNext !== false) {
        if (this.curStep == this.showSteps.length - 1) {
          // 处理页面关闭并跳转
          tagsViewStore.delView(this.$route)
          const codeStore = useCodeStore()
          codeStore.setIsPageInfoRefresh(true)
          this.$router.push({ name: 'PageInfo' })
        } else {
          ++this.curStep
        }
      }
    },
    handlePublishSaveSuccess() {
      this.publishFormInfo(this.handleSaveSuccess)
    }
  }
}
</script>
<style lang="scss" scoped>
.footer {
  display: flex;
  flex-direction: row;
  align-items: center;
  background-color: #fff;
  height: 80px;
  justify-content: center;
}
.header {
  display: flex;
  flex-direction: row;
  align-items: center;
  background-color: #fff;
  position: relative;

  .left {
    display: flex;
    align-items: center;

    i {
      cursor: pointer;
      margin-right: 4px;
    }

    .nameInfo {
      .title {
        font-size: 15px;
        color: #333333;
        margin-bottom: 4px;
      }

      .recent {
        font-size: 8px;
        color: #bbbbbb;
      }
    }
  }

  .middle {
    // display: block;
    // margin: 0 auto;
    width: 600px;
    gap: 18px;
    position: absolute;
    left: 50%;
    transform: translate(-50%, 0);

    .step {
      height: 30px;
      font-size: 13px;
      line-height: 30px;

      &:last-child {
        padding-left: 40px;
        border-left: 1px solid #d9d9d9;
      }
    }

    .active {
      background: #f2f3f8;
      border-radius: 30px;
      padding: 0px 10px;
      color: #3cc393;
      box-sizing: border-box;
    }
  }

  .right {
    margin-left: auto;
  }
}

.main {
  overflow-x: hidden;
  overflow-y: auto;

  .content {
    height: calc(100vh - 194px);
    // margin: 10px 220px;
    // background-color: #fff;
  }
  .databseDtyle {
    width: 80%;
    margin: 0px auto;
    background-color: rgb(255, 255, 255);
    margin-bottom: 20px;
    padding: 30px;
    box-sizing: border-box;
    span {
      padding-right: 50px;
    }
  }
}
</style>
